﻿// Copyright (c) 2023 raoyutian Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System;
using System.IO;
using System.Drawing;

namespace PaddleClasSharp
{
    /// <summary>
    /// 图像分类引擎对象
    /// </summary>
    public class PaddleClasEngine : EngineBase
    {
        #region PaddleClasEngine API

        [DllImport(dllName, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        internal static extern bool Initialize(string detmodelPath, string recmodelPath, string index_dir,string yaml_path, ClasParameter parameter);
       
        [DllImport(dllName, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        internal static extern IntPtr DetectionFile(string imagefile);
      
        [DllImport(dllName, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        internal static extern IntPtr DetectionByte(byte[] imagebytedata, long size);

        [DllImport(dllName, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        internal static extern IntPtr DetectionBase64(string base64);
      
        [DllImport(dllName, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        internal static extern int FreeEngine();
        #endregion

        /// <summary>
        /// 引擎对象初始化
        /// </summary>
        /// <param name="config">模型路径对象，为空按默认值</param>
        /// <param name="parameter">识别参数，为空均按缺省值</param>
        public PaddleClasEngine(ModelConfig config, ClasParameter parameter = null) : base()
        {
            if (parameter == null) parameter = new ClasParameter();
            if (config == null)
            {
                string root = GetRootDirectory();
                config = new ModelConfig();
#if NET35
                string modelPathroot = root + @"/models";
                config.det_infer = modelPathroot + @"/picodet_PPLCNet_x2_5_mainbody_lite_v1.0_infer";
                config.rec_infer = modelPathroot + @"/general_PPLCNetV2_base_pretrained_v1.0_infer";
                config.index_dir = modelPathroot + @"/index";
                config.yaml_file = modelPathroot + @"/inference.yaml";
#else
                string modelPathroot = Path.Combine(root, "models");
                config.det_infer = Path.Combine(modelPathroot, "picodet_PPLCNet_x2_5_mainbody_lite_v1.0_infer");
                config.rec_infer = Path.Combine(modelPathroot, "general_PPLCNetV2_base_pretrained_v1.0_infer");
                config.index_dir = Path.Combine(modelPathroot, "index");
                config.yaml_file = Path.Combine(modelPathroot, "inference.yaml");
#endif
            }
            if (!Directory.Exists(config.det_infer)) throw new DirectoryNotFoundException(config.det_infer);
            if (!Directory.Exists(config.rec_infer)) throw new DirectoryNotFoundException(config.rec_infer);
            if (!Directory.Exists(config.index_dir)) throw new DirectoryNotFoundException(config.index_dir);
            if (!File.Exists(config.yaml_file)) throw new FileNotFoundException(config.yaml_file);
          bool sucess =  Initialize(config.det_infer, config.rec_infer, config.index_dir, config.yaml_file, parameter);
          if(!sucess) throw new Exception("Initialize err:" + GetLastError());  
        }
       
        /// <summary>
        /// 检测图像文件
        /// </summary>
        /// <param name="imagefile">图像文件</param>
        /// <returns>检测结果</returns>
        public ClasResult Detection(string imagefile)
        {
            if (!File.Exists(imagefile)) throw new Exception($"文件{imagefile}不存在");
            var imagebyte = File.ReadAllBytes(imagefile);
            var result = Detection(imagebyte);
            imagebyte = null;
            return result;
        }
        /// <summary>
        /// 检测图像
        /// </summary>
        /// <param name="image">图像</param>
        /// <returns>检测结果</returns>
        public ClasResult Detection(Image image)
        {
            if (image == null) throw new ArgumentNullException("image");
            var imagebyte = ImageToBytes(image);
            var result = Detection(imagebyte);
            imagebyte = null;
            return result;
        }

        /// <summary>
        /// 检测图像bytes
        /// </summary>
        /// <param name="imagebyte">图像字节数组</param>
        /// <returns></returns>
        public ClasResult Detection(byte[] imagebyte)
        {
            if (imagebyte == null) throw new ArgumentNullException("imagebyte");
            var ptrResult = DetectionByte(imagebyte, imagebyte.LongLength);
            return ConvertResult(ptrResult);
        }
        /// <summary>
        ///检测图像base64
        /// </summary>
        /// <param name="imagebase64">图像base64</param>
        /// <returns>OCR识别结果</returns>
        public ClasResult Detection_Base64(string imagebase64)
        {
            if (imagebase64 == null || imagebase64 == "") throw new ArgumentNullException("imagebase64");
            IntPtr ptrResult = DetectionBase64(imagebase64);
            return ConvertResult(ptrResult);
        }
        /// <summary>
        /// 结果解析
        /// </summary>
        /// <param name="ptrResult"></param>
        /// <returns></returns>
        private ClasResult ConvertResult(IntPtr ptrResult)
        {
            ClasResult result = new ClasResult();
            try
            {
                if (ptrResult == IntPtr.Zero)
                {
                    var err = GetLastError();
                    if (err != "")
                    {
                        throw new Exception("内部遇到错误：" + err);
                    }
                    return result;
                }
                string json = Marshal.PtrToStringUni(ptrResult);
                result.JsonText = json;
                List<ObjectResult> objectResults = JsonHelper.DeserializeObject<List<ObjectResult>>(json);
                
                result.ObjectResults = objectResults;
                Marshal.FreeHGlobal(ptrResult);
            }
            catch (Exception ex)
            {
                throw new Exception("结果Json反序列化失败。", ex);
            }
            return result;
        }

        #region Dispose
        /// <summary>
        /// 释放对象
        /// </summary>
        public override void Dispose()
        {
            FreeEngine();
        }
        #endregion
    }
}